package com.fiberhome.app.network.socket;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Deed on 2018/1/9.
 */

public class DefaultTcpPacket implements TcpPacket {
    @Override
    public byte[] sendBytes(String sendData) {
        ByteArrayOutputStream bos = null;
        byte[] bytes = new byte[0];
        try {
            byte[] sendBytes = sendData.getBytes("ISO-8859-1");
            bos = new ByteArrayOutputStream();
            bos.write(int2Byte(sendBytes.length));
            bos.write(sendBytes);
            bytes = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }

    /**
     * @param intValue
     * @return byte[]
     */
    private byte[] int2Byte(int intValue) {

        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (intValue >> 8 * (3 - i) & 0xFF);
        }

        return b;
    }

    @Override
    public String getResult(InputStream is) {
        String resultStr = null;
        InputStream in = is;
        try {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(in));
            StringBuffer readBuffer = new StringBuffer();
            int len = -1;
            byte[] buffLen = new byte[4];
            len = in.read(buffLen);
            if (len != -1) {
                int jsonLen = byte2Int(buffLen);
                //大于1024长度
                byte[] b = new byte[jsonLen];
                int readCount = 0; // 已经成功读取的字节的个数
                while (readCount < jsonLen) {
                    readCount += in.read(b, readCount, jsonLen - readCount);
                }
                readBuffer.append(new String(b, 0, jsonLen));
            }

            bufferedReader.close();
            in.close();
            resultStr = readBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * byte2Int
     *
     * @param b byte[]
     * @return int
     */
    private int byte2Int(byte[] b) {
        int intValue = 0;
        for (int i = 0; i < b.length; i++) {
            intValue += (b[i] & 0xFF) << (8 * (3 - i));
        }
        return intValue;
    }
}
